package com.todo.pro.weixin;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.todo.pro.util.HttpUtils;
import com.todo.pro.weixin.model.WeiXinConfig;

public class WeiXinUtils {
	private final Logger logger = LoggerFactory.getLogger(WeiXinUtils.class);

	private WeiXinConfig weiXinConfig;

	public void setWeiXinConfig(WeiXinConfig weiXinConfig) {
		this.weiXinConfig = weiXinConfig;
	}

	public JSONObject getMpInfoByCode(String code) {
		if (StringUtils.isBlank(code)) {
			logger.error("Code不允许为空");
			return null;
		}
		String apiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
		String requestUrl = apiUrl.replaceAll("APPID", weiXinConfig.getMpAppId())
				.replaceAll("SECRET", weiXinConfig.getMpAppSecret()).replaceAll("JSCODE", code);

		String res = null;
		try {
			res = HttpUtils.sendGet(requestUrl, null);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("请求微信服务接口失败,E1!!!");
			return null;
		}
		if (res == null || res.length() < 1) {
			logger.error("请求微信服务接口失败,E3!!!");
			return null;
		}
		JSONObject json = null;
		try {
			json = JSONObject.parseObject(res);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("请求微信服务接口失败,E3!!!");
			return null;
		}
		if (json == null) {
			logger.error("请求微信服务接口失败,E4!!!");
			return null;
		}

		Integer errcode = json.getInteger("errcode");
		if (errcode != null && errcode.intValue() > 0) {
			logger.error("错误：E" + errcode + "，" + json.getString("errmsg"));
			return null;
		}
		return json;
	}

}
